package com.zhoulz.homework.chaptor02.node;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.io.File;
import java.io.FileInputStream;
import java.util.Arrays;

import org.apache.log4j.Logger;

import com.zhoulz.homework.chaptor02.config.Config;
import com.zhoulz.homework.chaptor02.node.Packet.PacketType;

/**
 * 客户端入站handler
 * @author zhoulz
 *
 */
public class PacketClientChannelInboundHandler extends SimpleChannelInboundHandler<ByteBuf> {
	Logger log = Logger.getLogger(PacketClientChannelInboundHandler.class);
	private String fromNodeName;
	private String toNodeName;
	
	private int unReceivedFileCount = 0;// 未接收完成的文件个数
	private boolean stop = false;

	public PacketClientChannelInboundHandler(String fromNodeName, String toNodeName) {
		this.fromNodeName = fromNodeName;
		this.toNodeName = toNodeName;
	}
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		File dataDir = new File(Config.DATA_DIR);
		File[] files = dataDir.listFiles();
		for (int i = 0; i < files.length; i++) {
			if(files[i].isDirectory())
				continue;
			File file = files[i];
			FileInputStream in = new FileInputStream(file);
			try {
				unReceivedFileCount++;
				// 设定发送包最大容量为65535
				int capacity = 0xFFFF;
				int length = 0;
				byte[] b = new byte[capacity];
				
				// 发送文件传输开始报文, 格式：节点名,文件名,文件大小
				byte[] data = fromNodeName.concat(",")
						.concat(file.getName()).concat(",")
						.concat(String.valueOf(file.length())).getBytes(Config.ENCODING);
				ctx.write(Unpooled.buffer(2).writeShort((short)data.length & capacity));
				ctx.write(Unpooled.buffer(1).writeByte(PacketType.FILE_SEND_START.getValue()));
				ctx.write(Unpooled.copiedBuffer(data));
				
				// 发送文件报文
				while((length = in.read(b)) != -1){
					ctx.write(Unpooled.buffer(2).writeShort((short)length & capacity));
					ctx.write(Unpooled.buffer(1).writeByte(PacketType.FILE_SEND_ING.getValue()));
					if(length < capacity){
						b = Arrays.copyOf(b, length);
					}
					ctx.write(Unpooled.copiedBuffer(b));
				}
				// 发送文件传输完成报文
				ctx.write(Unpooled.buffer(2).writeShort(1));
				ctx.write(Unpooled.buffer(1).writeByte(PacketType.FILE_SEND_DONE.getValue()));
				ctx.write(Unpooled.buffer(1).writeByte(1));
				System.out.println(String.format("To %s: %s[%d] ...", toNodeName, file, file.length()));
				ctx.flush();
			} catch (Exception e) {
				log.error(String.format("文件[%s]发送异常", file), e);
			}finally{
				in.close();
			}
			// FIXME 每次发送一个文件有问题咯~~~~，没时间了，下回再搞了，先做作业啊
//			super.channelActive(ctx);
//			// 每次仅传输1个文件
//			while(unReceivedFileCount > 0){
//				Thread.sleep(100);
//			}
//			System.out.println("send One File Done.");
			if(stop){
				break;
			}
			// 测试，发一个文件
//			 break;
		}
	}
	
	public void setStop(boolean stop) {
		this.stop = stop;
	}
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg)
			throws Exception {
		// 文件发送完成，或者接收到shutdown命令时安全关闭
		System.out.println("unCompleted:"+unReceivedFileCount);
		if(--unReceivedFileCount == 0 || (stop && msg.readByte() == PacketType.FILE_SEND_DONE.getValue())){
			ctx.close();
		}
	}
}
